"""
Smart prompt generator for hot topic based writing
"""
import logging
from typing import Dict, Any, List, Optional
from enum import Enum
from datetime import datetime

logger = logging.getLogger(__name__)

class HotTopicType(Enum):
    """Hot topic types"""
    EVENT = "event"  # 事件类
    TOPIC = "topic"  # 话题类 
    PERSON = "person"  # 人物类
    TREND = "trend"  # 趋势类
    CONTROVERSY = "controversy"  # 争议类

class WritingAngle(Enum):
    """Writing angles/perspectives"""
    NEWS_REPORT = "news_report"  # 新闻报道
    DEEP_ANALYSIS = "deep_analysis"  # 深度分析
    COMMENTARY = "commentary"  # 评论文章
    FEATURE_STORY = "feature_story"  # 专题报道
    OPINION_PIECE = "opinion_piece"  # 观点文章

class HotTopicPromptGenerator:
    """Generate smart prompts based on hot topics"""
    
    def __init__(self):
        """Initialize prompt generator with templates"""
        self.templates = self._init_templates()
        self.angle_suggestions = self._init_angle_suggestions()
        
    def _init_templates(self) -> Dict[HotTopicType, Dict[str, str]]:
        """Initialize prompt templates for different hot topic types

        注意：模板只包含任务描述，不包含具体数据（如title、excerpt）
        具体的热点数据由System Prompt提供
        """
        return {
            HotTopicType.EVENT: {
                "base": "针对当前热议话题，撰写一篇{angle}。",
                "context": "请从{perspective}的角度进行分析，重点关注{focus_points}。",
                "requirements": "文章要求：\n1. 客观陈述事实\n2. 多角度分析影响\n3. 提供深度见解\n4. 字数：{word_count}字左右"
            },
            HotTopicType.TOPIC: {
                "base": "针对当前热议话题，撰写一篇{angle}。",
                "context": "请围绕{key_points}展开讨论，体现{tone}的写作风格。",
                "requirements": "创作要求：\n1. 观点明确\n2. 论证充分\n3. 结构清晰\n4. 语言{style}"
            },
            HotTopicType.PERSON: {
                "base": "针对当前人物话题，撰写一篇{angle}，展现其{aspect}。",
                "context": "重点描述{highlights}，体现{narrative_style}。",
                "requirements": "写作要点：\n1. 生动刻画\n2. 事实准确\n3. 情感真实\n4. 故事性强"
            },
            HotTopicType.TREND: {
                "base": "针对当前趋势话题，撰写一篇{angle}。",
                "context": "从{dimensions}等维度进行分析，预测{future_impact}。",
                "requirements": "分析框架：\n1. 数据支撑\n2. 案例论证\n3. 趋势预判\n4. 建议措施"
            },
            HotTopicType.CONTROVERSY: {
                "base": "针对当前争议话题，撰写一篇{angle}。",
                "context": "平衡呈现{viewpoints}，理性分析{implications}。",
                "requirements": "写作原则：\n1. 立场中立\n2. 观点平衡\n3. 理性分析\n4. 建设性结论"
            }
        }
    
    def _init_angle_suggestions(self) -> Dict[HotTopicType, List[WritingAngle]]:
        """Initialize writing angle suggestions for each topic type"""
        return {
            HotTopicType.EVENT: [
                WritingAngle.NEWS_REPORT,
                WritingAngle.DEEP_ANALYSIS,
                WritingAngle.FEATURE_STORY
            ],
            HotTopicType.TOPIC: [
                WritingAngle.COMMENTARY,
                WritingAngle.OPINION_PIECE,
                WritingAngle.DEEP_ANALYSIS
            ],
            HotTopicType.PERSON: [
                WritingAngle.FEATURE_STORY,
                WritingAngle.DEEP_ANALYSIS,
                WritingAngle.NEWS_REPORT
            ],
            HotTopicType.TREND: [
                WritingAngle.DEEP_ANALYSIS,
                WritingAngle.COMMENTARY,
                WritingAngle.FEATURE_STORY
            ],
            HotTopicType.CONTROVERSY: [
                WritingAngle.OPINION_PIECE,
                WritingAngle.DEEP_ANALYSIS,
                WritingAngle.COMMENTARY
            ]
        }
    
    def identify_topic_type(self, title: str, excerpt: str = "") -> HotTopicType:
        """
        Identify the type of hot topic based on title and excerpt
        
        Args:
            title: Hot topic title
            excerpt: Topic excerpt/summary
            
        Returns:
            Identified topic type
        """
        text = f"{title} {excerpt}".lower()
        
        # Score each type based on keyword matches
        scores = {
            HotTopicType.EVENT: 0,
            HotTopicType.PERSON: 0,
            HotTopicType.CONTROVERSY: 0,
            HotTopicType.TREND: 0,
            HotTopicType.TOPIC: 0
        }
        
        # Event indicators
        event_keywords = ["发生", "事件", "突发", "爆发", "出现", "导致", "造成", "引发"]
        for kw in event_keywords:
            if kw in text:
                scores[HotTopicType.EVENT] += 2
        
        # Controversy indicators (check first for priority)
        controversy_keywords = ["争议", "质疑", "批评", "反对", "争论", "辩论", "分歧", "网友"]
        for kw in controversy_keywords:
            if kw in text:
                scores[HotTopicType.CONTROVERSY] += 2
        
        # Trend indicators
        trend_keywords = ["趋势", "潮流", "兴起", "流行", "增长", "下降", "变化", "发展", "分析"]
        for kw in trend_keywords:
            if kw in text:
                scores[HotTopicType.TREND] += 2
        
        # Person indicators
        person_keywords = ["某某", "先生", "女士", "明星", "专家", "领导", "创始人", "CEO"]
        for kw in person_keywords:
            if kw in text:
                scores[HotTopicType.PERSON] += 2
        
        # Check if title is likely a person name
        if self._is_person_name(title):
            scores[HotTopicType.PERSON] += 3
        
        # Special case: empty title/excerpt defaults to TOPIC
        if not title and not excerpt:
            return HotTopicType.TOPIC
        
        # Get type with highest score
        max_score = max(scores.values())
        if max_score == 0:
            return HotTopicType.TOPIC
        
        # Return type with highest score
        for topic_type, score in scores.items():
            if score == max_score:
                return topic_type
        
        return HotTopicType.TOPIC
    
    def _is_person_name(self, text: str) -> bool:
        """Check if text likely contains a person's name"""
        # Simple heuristic - could be enhanced with NER
        return len(text) <= 10 and not any(c in text for c in ["的", "了", "在", "是"])
    
    def generate_prompt(
        self,
        title: str,
        excerpt: str = "",
        topic_type: Optional[HotTopicType] = None,
        writing_angle: Optional[WritingAngle] = None,
        custom_params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Generate a smart prompt based on hot topic
        
        Args:
            title: Hot topic title
            excerpt: Topic excerpt/summary
            topic_type: Override auto-detected topic type
            writing_angle: Preferred writing angle
            custom_params: Custom parameters for template
            
        Returns:
            Generated prompt with metadata
        """
        # Identify topic type if not provided
        if topic_type is None:
            topic_type = self.identify_topic_type(title, excerpt)
        
        # Get suitable writing angles
        suggested_angles = self.angle_suggestions.get(
            topic_type,
            [WritingAngle.COMMENTARY]
        )
        
        # Use provided angle or select default
        if writing_angle is None:
            writing_angle = suggested_angles[0]
        
        # Get template
        template = self.templates.get(topic_type)
        if not template:
            template = self.templates[HotTopicType.TOPIC]
        
        # Prepare parameters
        params = self._prepare_parameters(
            title,
            excerpt,
            topic_type,
            writing_angle,
            custom_params
        )
        
        # Generate prompt components
        prompt_parts = []
        
        # Base prompt
        base_prompt = template["base"].format(**params)
        prompt_parts.append(base_prompt)
        
        # Context
        if "context" in template:
            context = template["context"].format(**params)
            prompt_parts.append(context)
        
        # Requirements
        if "requirements" in template:
            requirements = template["requirements"].format(**params)
            prompt_parts.append(requirements)
        
        # Combine prompt
        full_prompt = "\n\n".join(prompt_parts)
        
        # Return with metadata
        return {
            "prompt": full_prompt,
            "topic_type": topic_type.value,
            "writing_angle": writing_angle.value,
            "suggested_angles": [a.value for a in suggested_angles],
            "parameters": params,
            "generated_at": datetime.now().isoformat()
        }
    
    def _prepare_parameters(
        self,
        title: str,
        excerpt: str,
        topic_type: HotTopicType,
        writing_angle: WritingAngle,
        custom_params: Optional[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """Prepare template parameters"""
        # Base parameters
        params = {
            "title": title,
            "excerpt": excerpt or "暂无详细信息",
            "angle": self._get_angle_name(writing_angle),
        }
        
        # Type-specific parameters
        if custom_params is None:
            custom_params = {}
            
        if topic_type == HotTopicType.EVENT:
            params.update({
                "perspective": custom_params.get("perspective", "客观中立（例如：第三方观察者视角、当事人视角、行业专家视角）"),
                "focus_points": custom_params.get("focus_points", "起因、经过、影响（例如：政策背景、关键时间节点、社会反响）"),
                "word_count": custom_params.get("word_count", 1500)
            })
        elif topic_type == HotTopicType.TOPIC:
            params.update({
                "key_points": custom_params.get("key_points", "核心观点和论据（例如：技术革新带来的机遇与挑战、多方利益平衡）"),
                "tone": custom_params.get("tone", "理性客观（例如：深度思考、平衡分析、建设性批评）"),
                "style": custom_params.get("style", "流畅自然（例如：通俗易懂、引人入胜、逻辑严谨）")
            })
        elif topic_type == HotTopicType.PERSON:
            params.update({
                "aspect": custom_params.get("aspect", "成就与贡献（例如：科研突破、公益事业、行业引领）"),
                "highlights": custom_params.get("highlights", "关键事迹和特点（例如：重大项目经历、创新思维方式、人格魅力）"),
                "narrative_style": custom_params.get("narrative_style", "生动叙事风格（例如：故事化叙述、细节刻画、情感共鸣）")
            })
        elif topic_type == HotTopicType.TREND:
            params.update({
                "dimensions": custom_params.get("dimensions", "社会、经济、技术（例如：消费习惯变化、商业模式创新、AI技术应用）"),
                "future_impact": custom_params.get("future_impact", "未来发展趋势（例如：3-5年内的行业变革、政策导向影响）")
            })
        elif topic_type == HotTopicType.CONTROVERSY:
            params.update({
                "viewpoints": custom_params.get("viewpoints", "各方观点（例如：支持方论据、反对方顾虑、中立方建议）"),
                "implications": custom_params.get("implications", "深层影响（例如：价值观冲突、利益分配问题、社会规范重塑）")
            })
        
        # Override with custom params (but exclude complex objects)
        if custom_params:
            # Only update simple params, not complex objects like processed_comments
            for key, value in custom_params.items():
                # Skip complex objects that shouldn't be template parameters
                if key not in ['processed_comments', 'user_input']:
                    params[key] = value
        
        return params
    
    def _get_angle_name(self, angle: WritingAngle) -> str:
        """Get Chinese name for writing angle"""
        angle_names = {
            WritingAngle.NEWS_REPORT: "新闻报道",
            WritingAngle.DEEP_ANALYSIS: "深度分析",
            WritingAngle.COMMENTARY: "评论文章",
            WritingAngle.FEATURE_STORY: "专题报道",
            WritingAngle.OPINION_PIECE: "观点文章"
        }
        return angle_names.get(angle, "分析文章")
    
    def generate_batch_prompts(
        self,
        hot_topics: List[Dict[str, Any]],
        default_angle: Optional[WritingAngle] = None
    ) -> List[Dict[str, Any]]:
        """
        Generate prompts for multiple hot topics
        
        Args:
            hot_topics: List of hot topic data
            default_angle: Default writing angle
            
        Returns:
            List of generated prompts
        """
        prompts = []
        
        for topic in hot_topics:
            title = topic.get("title", "")
            excerpt = topic.get("excerpt", "")
            
            if title:
                prompt_data = self.generate_prompt(
                    title=title,
                    excerpt=excerpt,
                    writing_angle=default_angle
                )
                prompt_data["topic_rank"] = topic.get("rank", 0)
                prompt_data["hot_value"] = topic.get("hot_value", 0)
                prompts.append(prompt_data)
        
        return prompts
    
    def suggest_combined_prompt(
        self,
        hot_topics: List[Dict[str, Any]],
        max_topics: int = 3
    ) -> str:
        """
        Generate a combined prompt for multiple related hot topics
        
        Args:
            hot_topics: List of hot topic data
            max_topics: Maximum number of topics to combine
            
        Returns:
            Combined prompt string
        """
        # Select top topics
        selected_topics = hot_topics[:max_topics]
        
        if not selected_topics:
            return ""
        
        # Build combined prompt
        prompt_parts = ["请结合以下热点话题，撰写一篇综合性分析文章：\n"]
        
        for i, topic in enumerate(selected_topics, 1):
            title = topic.get("title", "")
            excerpt = topic.get("excerpt", "")
            hot_value = topic.get("hot_value", 0)
            
            prompt_parts.append(f"{i}. {title}")
            if hot_value:
                prompt_parts.append(f"   热度：{hot_value:,}")
            if excerpt:
                prompt_parts.append(f"   概述：{excerpt[:100]}...")
            prompt_parts.append("")
        
        prompt_parts.extend([
            "写作要求：",
            "1. 找出这些热点之间的关联性",
            "2. 分析共同反映的社会现象或趋势",
            "3. 提供独特的见解和观点",
            "4. 结构清晰，论述充分",
            "5. 字数2000-3000字"
        ])
        
        return "\n".join(prompt_parts)